package xyz.zenheart.ffmpegrelay.controller;

import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;

import java.nio.ByteBuffer;

/**
 * <p>项目名称: rtsp-face-master </p>
 * <p>描述: TODO </p>
 * <p>创建时间: 2021/9/7 </p>
 * <p>公司信息: 维之星研发部</p>
 *
 * @author CKM
 * @version v1.0
 */
public class RecordCollect3 {


    public static void frameRecord(String inputFile, String outputFile, boolean AUDIO_ENABLED) throws Exception {
        // 是否录制音频
        int audioChannel = AUDIO_ENABLED ? 1 : 0;
        // 获取视频源
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
//        grabber.setVideoCodec(avcodec.AV_CODEC_ID_MPEG1VIDEO);

//        grabber.setFormat("rtsp");
//        grabber.setPixelFormat(ARToolKitPlus.PIXEL_FORMAT_RGB);
        // 流媒体输出地址，分辨率（长，高），是否录制音频（0:不录制/1:录制）
        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, 720, 600, audioChannel);
        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); // avcodec.AV_CODEC_ID_H264，编码
        recorder.setFormat("flv");//封装格式，如果是推送到rtmp就必须是flv封装格式
//        recorder.setPixelFormat(avutil.AV_PIX_FMT_RGBA);
        // 开始取视频源
//        avutil.av_log_set_level(avutil.AV_LOG_ERROR);
        recordByFrame(grabber, recorder, AUDIO_ENABLED);
    }

    private static void recordByFrame(FFmpegFrameGrabber grabber, FFmpegFrameRecorder recorder, Boolean status) throws Exception {
        try {  //建议在线程中使用该方法

            grabber.start();
            recorder.start();
            Frame frame;
            while (status && (frame = grabber.grabFrame()) != null) {
                ByteBuffer data = grabber.grabFrame().data;
                byte[] array = data.array();
                recorder.record(frame);
            }
            recorder.stop();
            grabber.stop();
        } finally {
            if (grabber != null) {
                grabber.stop();
            }
        }
    }


    public static void main(String[] args)
            throws Exception {

        String inputFile = "rtsp://admin:admin@192.168.1.59:554/";
        // Decodes-encodes
        String outputFile = "C:\\Users\\reality\\Desktop\\src\\output1.mp4";
        frameRecord(inputFile, outputFile, true);
    }
}
